﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.System.Dtos.DictionaryData;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller.System
{
    /// <summary>
    /// 字典数据
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.09.21 
    /// </summary>
    [Route("api/System/[controller]")]
    public class DictionaryDataController : BaseApiController
    {
        private DictionaryDataBll dictionaryDataBll = new DictionaryDataBll();
        private DictionaryTypeBll dictionaryTypeBll = new DictionaryTypeBll();

        #region GET
        /// <summary>
        /// 获取数据字典列表
        /// </summary>
        /// <param name="dictionaryTypeId">分类id</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpGet("{dictionaryTypeId}")]
        public async Task<ResponseResult> GetList(string dictionaryTypeId, DictionaryDataListQuery input)
        {
            var data = await dictionaryDataBll.GetList(dictionaryTypeId);
            if (!string.IsNullOrEmpty(input.keyword))
            {
                data = data.FindAll(t => t.EnCode.Contains(input.keyword) || t.FullName.Contains(input.keyword));
            }
            if ("1".Equals(input.isTree))
            {
                var treeList = data.MapToList<DictionaryDataTreeOutput>();
                return Success(new { list = treeList.ToTree() });
            }
            else
            {
                var treeList = data.MapToList<DictionaryDataListOutput>();
                return Success(new { list = treeList });
            }

        }

        /// <summary>
        ///获取所有数据字典列表(分类+内容)
        /// </summary>
        /// <returns></returns>
        [HttpGet("All")]
        public async Task<ResponseResult> GetListAll()
        {
            var dictionaryData = await dictionaryDataBll.GetList();
            var dictionaryType = await dictionaryTypeBll.GetList();
            var data = dictionaryType.MapToList<DictionaryDataAllListOutput>();
            data.ForEach(dataall =>
            {
                if (dataall.isTree.Equals("1"))
                {
                    dataall.dictionaryList = dictionaryData.FindAll(d => d.DictionaryTypeId == dataall.id).MapToList<DictionaryDataTreeOutput>();
                }
                else
                {
                    dataall.dictionaryList = dictionaryData.FindAll(d => d.DictionaryTypeId == dataall.id).MapToList<DictionaryDataListOutput>();
                }
            });
            return Success(new { list = data });

        }

        /// <summary>
        ///获取字典分类下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet("{dictionaryTypeId}/Selector")]
        public async Task<ResponseResult> GetSelector(string dictionaryTypeId, string isTree)
        {
            var output = new List<DictionaryDataSelectorOutput>();
            var typeEntity = await dictionaryTypeBll.GetInfo(dictionaryTypeId);
            //顶级节点
            var dataEntity = typeEntity.MapTo<DictionaryDataSelectorOutput>();
            dataEntity.id = "0";
            dataEntity.parentId = "-1";
            output.Add(dataEntity);
            if ("1".Equals(isTree))
            {
                var dataList = (await dictionaryDataBll.GetList(dictionaryTypeId)).MapToList<DictionaryDataSelectorOutput>();
                output = output.Union(dataList).ToList();
                return Success(new { list = output.ToTree("-1") });
            }
            return Success(new { list = output });
        }

        /// <summary>
        ///获取字典数据下拉框列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("{dictionaryTypeId}/Data/Selector")]
        [AllowAnonymous]
        public async Task<ResponseResult> GetDataSelector(string dictionaryTypeId)
        {
            var isTree = (await dictionaryTypeBll.GetInfo(dictionaryTypeId)).IsTree;
            var data = await dictionaryDataBll.GetList(dictionaryTypeId);
            var datalist = data.FindAll(d => d.EnabledMark == 1);
            var treeList = datalist.MapToList<DictionaryDataSelectorDataOutput>();
            if (isTree == 1)
            {
                treeList = treeList.ToTree();
            }
            return Success(new { list = treeList });
        }

        /// <summary>
        /// 获取按钮信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        [HttpGet("{id}/Info")]
        public async Task<ResponseResult> GetInfo(string id)
        {
            var data = await dictionaryDataBll.GetInfo(id);
            var output = data.MapTo<DictionaryDataInfoOutput>();
            return Success(output);
        }
        #endregion

        #region Post
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Creater([FromBody] DictionaryDataCrInput input)
        {
            if (await dictionaryDataBll.IsExistByEnCode(input.dictionaryTypeId, input.enCode, null))
            {
                return Error("编码已存在");
            }
            if (await dictionaryDataBll.IsExistByFullName(input.dictionaryTypeId, input.fullName, null))
            {
                return Error("名称已存在");
            }
            var entity = input.MapTo<DictionaryDataEntity>();
            var isOk = await dictionaryDataBll.Create(entity);
            return isOk > 0 ? Success("新建成功") : Error("新建失败");
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResponseResult> Update(string id, [FromBody] DictionaryDataUpInput input)
        {
            if (await dictionaryDataBll.IsExistByEnCode(input.dictionaryTypeId, input.enCode, id))
            {
                return Error("编码已存在");
            }
            if (await dictionaryDataBll.IsExistByFullName(input.dictionaryTypeId, input.fullName, id))
            {
                return Error("名称已存在");
            }
            var entity = input.MapTo<DictionaryDataEntity>();
            var isOk = await dictionaryDataBll.Update(id, entity);
            return isOk > 0 ? Success("修改成功") : Error("修改失败");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(string id)
        {
            var entity = await dictionaryDataBll.GetInfo(id);
            if (entity == null)
            {
                return Error("数据不存在");
            }
            await dictionaryDataBll.Delete(entity);
            return Success("删除成功");
        }

        /// <summary>
        /// 更新字典状态
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpPut("{id}/Actions/State")]
        public async Task<ResponseResult> ActionsState(string id)
        {
            var entity = await dictionaryDataBll.GetInfo(id);
            entity.EnabledMark = entity.EnabledMark == 0 ? 1 : 0;
            var isOk = await dictionaryDataBll.Update(id, entity);
            return isOk > 0 ? Success("更新状态成功") : Error("更新状态失败");
        }
        #endregion
    }
}
